package com.xuhuan.algorithm.demo1;

/**
 * @author huan.xu
 * @ClassName Demo1Code
 * @date 2021/4/22 15:14
 * @Description 二分查找
 * 搜索一个数，如果存在，返回其索引，否则返回 -1。
 */
public class Demo1Code {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 9};
        System.out.println(binarySearch(1, nums));
    }

    /**
     * 二分查找方法
     *
     * @param target
     * @param nums
     * @return
     */
    private static int binarySearch(int target, int[] nums) {
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int mid = (right + left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }


}
